// pages/cart/cart.js
Page({
  data: {
    state:0,
    sumary:'0.00',
    number:0,
    list: [{ state: 0, id: '15689', pid: '1288', src: '../img/pro.jpg', name: '自助晚餐', price: '66', num: 2 }, { state: 0, id: '15689', pid: '1288', src: '../img/pro.jpg', name: '自助晚餐', price: '66', num:2 }]
  },
  less: function (e) {
    var that = this;
    let index = e.currentTarget.dataset.index;
    let val = that.data.list[index].num;
    if (val > 1) {
      that.setData({
        ['list[' + index + '].num']: val - 1
      });
      that.total();
    } else {
      var that = this;
      wx.showModal({
        title: '提示',
        content: '确定要从购物车删除该商品？',
        success: function (sm) {
          if (sm.confirm) {
            var data = that.data.list;
            data.splice(index, 1);
            that.setData({
              list: data
            });
            that.total();
          } else if (sm.cancel) {
          }
        }
      })
    }
  },
  more: function (e) {
    var that = this;
    let index = e.currentTarget.dataset.index;
    let val = that.data.list[index].num;
    that.setData({
      ['list[' + index + '].num']: val + 1
    });
    that.total();
  },
  pick:function(e){
    var that = this;
    let index = e.currentTarget.dataset.index;  
    let val = that.data.list[index].state;
    that.setData({
      ['list[' + index + '].state']:val==1?0:1
    }); 
    that.total();
  },
  toggle:function(){
    var that=this;
    var now=this.data.state;
    if(now==0){
      that.setData({
       state:1
      }); 
      var datas = that.data.list;
      for (var i = 0; i < datas.length; i++) {
        that.setData({ ['list[' + i + '].state']:1});
      };
      that.total();
    }else{
      that.setData({
        state: 0
      }); 
      var datas = that.data.list;
      for (var i = 0; i < datas.length; i++) {
        that.setData({ ['list[' + i + '].state']:0 });
      };
      that.total();
    }
  },
  total:function(){
    var that=this;
    var datas = that.data.list;
    var prices = 0;
    var nums=0;
    for (var i = 0; i < datas.length; i++) {
      if (datas[i].state==1){
        prices += datas[i].num * datas[i].price;
        nums += datas[i].num;
      }
      if (i == datas.length-1) {
        prices = prices.toFixed(2);
      }
      that.setData({ sumary: prices, number:nums });
    };
  },
  submit: function () {
    wx.navigateTo({
      url: '../deals/deals',
    })

  },
  onLoad: function (options) {
  
  },
  onReady: function () {
  
  }
})